<template>
  <div class="loginpage">
    <h3>{{ $t(`login.title`) }}</h3>
    <el-form :model="userform" label-position="left" :rules="rules" ref="loginref">
      <el-form-item prop="username">
        <el-input v-model="userform.username" :prefix-icon="User" placeholder="请输入用户名" />
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          v-model="userform.password"
          type="password"
          placeholder="请输入密码"
          show-password
          :prefix-icon="Key"
        />
      </el-form-item>
    </el-form>
    <el-button type="primary" class="login-btn" @click="login">{{ $t(`login.btnTitle`) }}</el-button>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, ref, toRaw } from 'vue'
import { useRouter } from 'vue-router'

import { User, Key } from '@element-plus/icons-vue'
import type { FormInstance } from 'element-plus'
import { ElMessage } from 'element-plus'

import { loginfn } from '../../server/login'
import { LoginStore } from '../../store/login'
import { LocalCache } from '../../utils/LocalCache'
import { setTokenTime } from '../../utils/auth'
export default defineComponent({
  setup() {
    const router = useRouter()
    const loginref = ref<FormInstance>()
    const LoginInfo = LoginStore()
    const userform = reactive({
      username: 'admin',
      password: '123456'
    })
    const rules = reactive({
      username: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
      password: [{ required: true, message: '密码不能为空', trigger: 'blur' }]
    })

    // 登录
    const login = async () => {
      setTokenTime(Date.now())
      await loginref.value?.validate((valid, fields) => {
        if (valid) {
          loginfn(toRaw(userform)).then((res: any) => {
            if (res.meta.status !== 200) {
              ElMessage.error('用户名或密码有误!')
            } else {
              ElMessage({
                message: '登录成功',
                type: 'success',
                offset: 60
              })
              LoginInfo.changeUserInfo(res.data)
              LocalCache.setitem('token', res.data.token)
              router.push('/main')
            }
          })
        } else {
          console.log('error submit!', fields)
        }
      })
    }
    return {
      userform,
      User,
      Key,
      rules,
      loginref,
      login,
      LoginInfo
    }
  }
})
</script>

<style lang="scss" scoped>
.loginpage {
  width: 340px;
  position: absolute;
  left: 50%;
  top: 40%;
  transform: translate(-50%, -50%);
  text-align: center;
  h3 {
    margin-bottom: 20px;
    text-align: center;
    color: #fff;
  }
}
.el-input {
  text-indent: 2em !important;
  --el-input-focus-border-color: none !important;
}
.login-btn {
  width: 100%;
}
</style>
